"""API网关中间件"""
from flask import Flask, request, jsonify
from utils.logger import setup_application_logging
from utils.auth import AuthManager
from utils.response import create_response
from utils.exceptions import AuthenticationException, ValidationException

class APIGateway:
    """API网关类"""
    
    def __init__(self, app: Flask = None):
        """初始化API网关"""
        self.app = app
        self.auth_manager = None  # 将在init_app中设置
        self.logger = setup_application_logging()
        
        if app is not None:
            self.init_app(app)
    
    def init_app(self, app: Flask):
        """初始化Flask应用"""
        self.app = app
        # 使用app的auth_manager
        self.auth_manager = getattr(app, 'auth_manager', None)
        
        # 注册中间件
        app.before_request(self.before_request)
        app.after_request(self.after_request)
        app.errorhandler(Exception)(self.handle_error)
    
    def before_request(self):
        """请求前处理"""
        try:
            # 记录请求信息
            self.logger.info(f"Request: {request.method} {request.url}")
            
            # 跳过不需要认证的路径
            if self._is_public_endpoint(request.endpoint):
                return
            
            # API密钥验证
            api_key = request.headers.get('X-API-Key')
            if not api_key:
                response_data, status_code = create_response(
                    success=False,
                    error_message="缺少API密钥",
                    error_code="MISSING_API_KEY"
                )
                return jsonify(response_data), status_code
            
            if not self.auth_manager.validate_api_key(api_key):
                response_data, status_code = create_response(
                    success=False,
                    error_message="无效的API密钥",
                    error_code="INVALID_API_KEY"
                )
                return jsonify(response_data), status_code
                
        except Exception as e:
            self.logger.error(f"请求前处理错误: {str(e)}")
            response_data, status_code = create_response(
                success=False,
                error_message="服务器内部错误",
                error_code="INTERNAL_ERROR"
            )
            return jsonify(response_data), status_code
    
    def after_request(self, response):
        """请求后处理"""
        try:
            # 记录响应信息
            self.logger.info(f"Response: {response.status_code}")
            
            # 添加CORS头
            response.headers['Access-Control-Allow-Origin'] = '*'
            response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
            response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-API-Key'
            
            return response
            
        except Exception as e:
            self.logger.error(f"请求后处理错误: {str(e)}")
            return response
    
    def handle_error(self, error):
        """错误处理"""
        self.logger.error(f"API错误: {str(error)}")
        
        if isinstance(error, AuthenticationException):
            response_data, status_code = create_response(
                success=False,
                error_message=str(error),
                error_code="AUTHENTICATION_ERROR"
            )
            return jsonify(response_data), status_code
        elif isinstance(error, ValidationException):
            response_data, status_code = create_response(
                success=False,
                error_message=str(error),
                error_code="VALIDATION_ERROR"
            )
            return jsonify(response_data), status_code
        else:
            response_data, status_code = create_response(
                success=False,
                error_message="服务器内部错误",
                error_code="INTERNAL_ERROR"
            )
            return jsonify(response_data), status_code
    
    def _is_public_endpoint(self, endpoint):
        """检查是否为公开端点"""
        public_endpoints = [
            'health_check',
            'api_docs',
            'swagger_ui',
            'static',
            'flasgger.apidocs',
            'flasgger.static',
            'flasgger.oauth_redirect',
            'flasgger.<lambda>',
            'flasgger.apispec',
            'admin.get_system_status',
            'admin.get_system_logs',
            'admin.generate_api_key',
            'chain.get_supported_chains'  # 添加chains端点为公开端点
        ]
        
        if endpoint is None:
            return False
            
        return any(public in endpoint for public in public_endpoints)
    
    def get_system_status(self):
        """获取系统状态"""
        import time
        import os
        
        return {
            'version': '1.0.0',
            'uptime': int(time.time()),
            'active_connections': 1,
            'memory_usage': {'used': '100MB', 'total': '1GB'},
            'cpu_usage': 15.5,
            'chain_status': {
                'fisco_bcos': 'active',
                'chainmaker': 'active',
                'jdchain': 'active',
                'thanos': 'active',
                'xuperchain': 'active'
            }
        }
    
    def get_system_logs(self, level='info', limit=100, start_time=None, end_time=None):
        """获取系统日志"""
        import datetime
        
        # 模拟日志数据
        logs = []
        for i in range(min(limit, 10)):
            logs.append({
                'timestamp': datetime.datetime.now().isoformat(),
                'level': level,
                'message': f'Sample log message {i+1}',
                'module': 'blockchain_middleware',
                'details': {'component': 'api_gateway'}
            })
        
        return logs
